package com.chunuo.configuration.utils;


import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.net.URLDecoder;

/**
 * 注解工具类
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-04-13 22:30
 */
public class AnnotationUtils {

    /**
     * 得到指定路径下的绝对路径
     * @param packageName 指定的包路径
     * @return
     */
    public static String getPath(String packageName){
        //得到项目classpath路径
        String path = AnnotationUtils.class.getResource("/").getPath();
        try {
            path = URLDecoder.decode(path,"utf-8");//转译为utf-8
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //得到绝对路径
        String searchPath = path + packageName;

        return searchPath;

    }

    /**
     * 驼峰命名法
     * @param field
     * @return
     */
    public static String hump(String field){
        String tableName = AnnotationUtils.toLowerCaseFirstOne(field);
        StringBuffer name = new StringBuffer();
        for(int i = 0;i<tableName.length();i++){
            if(tableName.charAt(i)>='A'&&tableName.charAt(i)<='Z'){
                name.append("_"+(char)(tableName.charAt(i)+32));
            }else{
                name.append(tableName.charAt(i));
            }
        }
        return name.toString();
    }

    /**
     * clazz 得到类名并首字母小写
     * @param clazz
     * @return
     */
    public static String getClassName(Class clazz){
        String name = clazz.toString().split(" ")[1];
        return toLowerCaseFirstOne(name.substring(name.lastIndexOf(".")+1));
    }

    /**
     * 获取注解value
     * @param annotation
     * @return
     */
    public static String getAnnotationName(Annotation annotation){
        return annotation.toString().substring(annotation.toString().lastIndexOf("value=")+"value=".length(),annotation.toString().length()-1);
    }

    public static String getAnnotationName(String annotation){
        return annotation.substring(annotation.lastIndexOf("value=")+"value=".length(),annotation.length()-1);
    }

    //首字母转小写
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

}
